package com.cash.channel.svc.util;

import com.alibaba.fastjson.JSON;
import com.cash.channel.api.exception.CashChannelException;
import com.cash.channel.api.service.BaseApi;
import com.cash.channel.svc.config.ApplicationContextRegister;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.util.Arrays;
import org.springframework.context.ApplicationContext;

/**
 * @blame taihao
 */
public class ServiceUtils {

    private static Log logger = LogFactory.getLog(ServiceUtils.class);

    public static BaseApi getApiService(String key) throws CashChannelException {
        Object obj = getBean(key);
        if (obj instanceof BaseApi) {
            return (BaseApi) obj;
        } else {
            throw new CashChannelException(String.format("服务[%s]类型错误,请联系管理员", key));
        }
    }

    private static Object getBean(String key) throws CashChannelException {
        ApplicationContext applicationContext = ApplicationContextRegister.getApplicationContext();
        Object obj = applicationContext.getBean(key);
        if (obj == null) {
            throw new CashChannelException(String.format("服务[%s]未找到", key));
        }
        return obj;
    }

    public static <T> T getBean(String key, Class<T> clazz) throws CashChannelException {
        Object obj = getBean(key);
        logger.info(JSON.toJSONString(obj.getClass().getInterfaces()));
        logger.info(JSON.toJSONString(obj.getClass().getPackage()));
        if (ArrayUtils.contains(obj.getClass().getInterfaces(), clazz)) {
            return clazz.cast(obj);
        } else {
            throw new CashChannelException(String.format("服务[%s]类型错误,请联系管理员", key));
        }
    }

}
